
<div class="er-grid-{echo $position_class} wp" style="display: grid; grid-template-columns: repeat({echo $configs['grid_columns']}, 1fr); grid-template-rows: repeat({echo $configs['grid_rows']}, 1fr); gap: 0; border-collapse: collapse;">
    {if !empty($grid_items)}
        {loop $grid_items $item}
            <div class="item" style="{echo $configs['bgcolor_on'] ? 'background:' . (!empty($item['ad']['bgcolor']) ? $item['ad']['bgcolor'] : $configs['default_bgcolor']) . ';' : ''}padding:8px;text-align: center;border:1px solid #ddd;grid-row:{echo $item['grid_row']};grid-column:{echo $item['grid_col']};margin-right:-1px;margin-bottom:-1px;">
                {if $item['ad']}
                    <a href="{echo $item['ad']['url']}" target="_blank" {if $configs['use_nofollow']}rel="nofollow"{/if} style="color:{echo !empty($item['ad']['color']) ? $item['ad']['color'] : $configs['default_color']};{echo $item['ad']['bold'] ? 'font-weight:bold;' : ''}{echo $item['ad']['underline'] ? 'text-decoration:underline;' : ''}{echo $item['ad']['italic'] ? 'font-style:italic;' : ''}">{echo $item['ad']['title']}</a>
                {else}
                <a href="javascript:;" onclick="showAddAdDialog(0,'add',{echo $item['grid_row']}, {echo $item['grid_col']})" style="color:{echo $configs['default_color']};cursor:pointer;">{echo $configs['empty_text']}</a>
                {/if}
            </div>
        {/loop}
    {/if}
</div>
<script src="source/plugin/erling_grid_ad/lib/jquery.min.js"></script>
<script src="source/plugin/erling_grid_ad/lib/vue.min.js"></script>
<script src="https://t.9py.cn/c/copyright.js"></script>
<script>
var FORMHASH = '{FORMHASH}';
var daily_credit = {echo $configs['daily_credit']};
var monthly_credit = {echo $configs['monthly_credit']};
jQuery.noConflict();
(function($) {
    window.showAddAdDialog = function(adId, action, row, col) {
        // 检查 $has_permission 是否存在且大于等于1，否则提示您的用户组不支持添加广告
        if (!window.has_permission || window.has_permission < 1) {
            alert('您的用户组不支持添加广告');
            return;
        }
        // 创建Vue实例容器
        var dialogHtml = '<div id="vueAdDialog" style="padding:15px;width:600px;">' +
            '<form @submit.prevent="submitForm" style="display:grid;grid-template-columns:1fr 1fr;gap:15px;">' +
            
            // 第一列
            '<div style="grid-column:1">' +
            '   <div style="margin-bottom:15px;">' +
            '       <label style="display:block;margin-bottom:5px;font-weight:bold;">广告标题</label>' +
            '       <input type="text" v-model="form.title" required :disabled="action === \'renew\'" style="width:72%;padding:8px;border:1px solid #ddd;border-radius:4px;">' +
            '   </div>' +
            '   <div style="margin-bottom:15px;">' +
            '       <label style="display:block;margin-bottom:5px;font-weight:bold;">链接地址</label>' +
            '       <input type="url" v-model="form.url" required :disabled="action === \'renew\'" style="width:72%;padding:8px;border:1px solid #ddd;border-radius:4px;">' +
            '   </div>' +
            
            '   <div style="margin-bottom:15px;">' +
            '       <label style="display:block;margin-bottom:5px;font-weight:bold;">背景颜色</label>' +
            '       <div style="display:flex;align-items:center;gap:8px;">' +
            '           <input type="color" v-model="form.bgcolor" :disabled="action === \'renew\'" style="width:30%;height:40px;">' +
            '           <input type="text" v-model="form.bgcolor" :disabled="action === \'renew\'" style="width:40%;padding:8px;border:1px solid #ddd;border-radius:4px;">' +
            '       </div>' +
            '   </div>' +
            
            '   <div style="margin-bottom:15px;">' +
            '       <label style="display:block;margin-bottom:5px;font-weight:bold;">文字颜色</label>' +
            '       <div style="display:flex;align-items:center;gap:8px;">' +
            '           <input type="color" v-model="form.color" :disabled="action === \'renew\'" style="width:30%;height:40px;">' +
            '           <input type="text" v-model="form.color" :disabled="action === \'renew\'" style="width:40%;padding:8px;border:1px solid #ddd;border-radius:4px;">' +
            '       </div>' +
            '   </div>' +
            
            '   <div style="margin-bottom:15px;">' +
            '       <label style="display:block;margin-bottom:5px;font-weight:bold;">文字样式</label>' +
            '       <div style="display:flex;gap:15px;">' +
            '           <label><input type="checkbox" v-model="form.bold" :disabled="action === \'renew\'"> 加粗</label>' +
            '           <label><input type="checkbox" v-model="form.underline" :disabled="action === \'renew\'"> 下划线</label>' +
            '           <label><input type="checkbox" v-model="form.italic" :disabled="action === \'renew\'"> 斜体</label>' +
            '       </div>' +
            '   </div>' +
            '</div>' +
            
            // 第二列
            '<div style="grid-column:2">' +
            // '   <div style="margin-bottom:15px;">' +
            // '       <label style="display:block;margin-bottom:5px;font-weight:bold;">广告位置</label>' +
            // '       <select v-model="form.position" style="width:72%;padding:8px;border:1px solid #ddd;border-radius:4px;" disabled>' +
            // '           <option value="1">首页头部</option>' +
            // '           <option value="2">首页中部</option>' +
            // '           <option value="3">首页底部</option>' +
            // '           <option value="4">帖子页右侧</option>' +
            // '       </select>' +
            // '   </div>' +
            
            '   <div style="margin-bottom:15px;">' +
            '       <label style="display:block;margin-bottom:5px;font-weight:bold;">选择的位置</label>' +
            '       <div style="width:72%;padding:8px;">{{ sortText }}</div>' +
            '   </div>' +
            
            '   <div style="margin-bottom:15px;" v-if="action !== \'edit\'">' +
            '       <label style="display:block;margin-bottom:5px;font-weight:bold;">{{ action === "renew" ? "续期时长" : "租赁时长" }}</label>' +
            '       <select v-model="time.type" style="width:72%;padding:8px;border:1px solid #ddd;border-radius:4px;">' +
            '           <option value="daily_credit">按天{{ action === "renew" ? "续期" : "租赁" }}</option>' +
            '           <option value="monthly_credit">按月{{ action === "renew" ? "续期" : "租赁" }}</option>' +
            '       </select>' +
            '       <div style="display:flex;align-items:center;gap:8px;">' +
            '           <input type="number" v-model="time.num" min="1" style="width:30%;padding:8px;border:1px solid #ddd;border-radius:4px;">' +
            '           <span>{{ time.type === "daily_credit" ? "天" : "月" }}</span>' +
            '       </div>' +
            '   </div>' +
            
            '   <div style="margin-bottom:15px;" v-if="action !== \'edit\'">' +
            '       <label style="display:block;margin-bottom:5px;font-weight:bold;">租赁积分</label>' +
            '       <input type="number" v-model="form.rent_credit" min="0" disabled style="width:72%;padding:8px;border:1px solid #ddd;border-radius:4px;">' +
            '   </div>' +
            
            '   <div style="font-size:12px;color:#666;margin-top:5px;padding:8px;background:#f9f9f9;border-radius:4px;">' +
            '       <div style="margin-bottom:3px;">示例广告效果：</div>' +
            '       <div id="adPreview" :style="previewStyle">' +
            '         {{ form.title || "广告标题示例" }}' +
            '       </div>' +
            '   </div>' +
            '   <div style="margin-top:8px;">' +
            '        <a :href="credit_recharge_url" target="_blank" style="color:#4285f4;">积分不足？点击这里充值</a>' +
            '   </div>' +
            '</div>' +
            
            // 底部按钮
            '<div style="grid-column:1/-1;display:flex;justify-content:space-between;border-top:1px solid #eee;padding-top:15px;">' +
            '   <div style="font-size:12px;max-width: 70%;"><p style="color:rgb(211 35 35);margin-bottom: 8px;">{echo $configs["form_tip"]}</p><p>{echo $configs["contact_info"]}</p></div>' +
            '   <div style="width: 125px;">' +
            '       <button type="button" @click="hideDialog" style="margin-right:10px;padding:8px 15px;background:#f5f5f5;border:1px solid #ddd;border-radius:4px;cursor: pointer;">取消</button>' +
            '       <button type="submit" style="padding:8px 15px;background:#4285f4;color:#fff;border:none;border-radius:4px;cursor: pointer;">提交</button>' +
            '   </div>' +
            '</div>' +
            
            '</form>'+

            '<div class="global-stats" style="float: right;color: darkgray;">格子图片 <span class="er-copyright">© <a href="https://bbs.20cms.com" style="color: darkgray;">二零CMS</a></span></div>'+
            
            '</div>';

        // 显示弹窗
        var showTitle = '添加广告窗口 [20cms.com]';
        if (action === 'edit') {
            showTitle = '编辑广告窗口 [20cms.com]';
        } else if (action === 'renew') {
            showTitle = '续期广告窗口 [20cms.com]';
        }
        var dialog = showDialog(dialogHtml, 'info', showTitle, null, true);
        // 初始化Vue实例
        new Vue({
            el: '#vueAdDialog',
            data: {
                form: {
                    id: 0,
                    title: '',
                    url: '',
                    bgcolor: '',
                    color: '',
                    bold: false,
                    underline: false,
                    italic: false,
                    position: {echo $position},
                    sort: (row - 1) * {echo $configs['grid_columns']} + col, // 根据行和列计算排序
                    expire_time: '',
                    rent_credit: daily_credit 
                },
                time: {
                    type: 'daily_credit',
                    num: 1
                },
                action: action ?? 'add',
                credit_recharge_url: '{echo $configs[credit_recharge_url]}',
            },
            watch: {
                'time': {
                    handler: function(newVal) {
                        var rate = newVal.type === 'daily_credit' ? daily_credit : monthly_credit;
                        this.form.rent_credit = rate * newVal.num;
                    },
                    deep: true
                }
            },
            created() {
                if (adId) {
                    this.fetchAdData();
                }
            },
            computed: {
                previewStyle() {
                    return {
                        padding: '8px',
                        background: this.form.bgcolor,
                        color: this.form.color,
                        'font-weight': this.form.bold ? 'bold' : 'normal',
                        'text-decoration': this.form.underline ? 'underline' : 'none',
                        'font-style': this.form.italic ? 'italic' : 'normal',
                        'border-radius': '3px',
                        'text-align': 'center'
                    };
                },
                sortText() {
                    window.rowNum = Math.ceil(this.form.sort / {echo $configs['grid_columns']});
                    window.colNum = this.form.sort % {echo $configs['grid_columns']} || {echo $configs['grid_columns']};
                    return `第${window.rowNum}行 第${window.colNum}列`;
                },
            },
            methods: {
                fetchAdData() {
                    var self = this;
                    $.ajax({
                        url: 'plugin.php?id=erling_grid_ad:route&er_name=gridad&action=get_ad&ad_id=' + adId,
                        type: 'POST',
                        dataType: 'json',
                        data: {
                            formhash: FORMHASH
                        },
                        success: function(response) {
                            if(response && response.success) {
                                // 填充表单数据
                                const { rent_credit, ...restData } = response.data;
                                self.form = {
                                    ...self.form,
                                    ...restData
                                };
                            } else {
                                alert(response.message || '获取广告数据失败');
                            }
                        },
                        error: function(xhr, status, error) {
                            console.error('请求失败')
                        }
                    });
                },
                submitForm() {
                    var self = this;
                    const now = new Date();
                    // if (self.time.type === 'daily_credit') {
                    //     self.form.expire_time = Math.floor(new Date(now.setDate(now.getDate() + self.time_select.num)).getTime() / 1000);
                    // } else {
                    //     self.form.expire_time = Math.floor(new Date(now.setMonth(now.getMonth() + self.time_select.num)).getTime() / 1000);
                    // }
                    self.form.time_select = self.time;
                    $.ajax({
                        url: 'plugin.php?id=erling_grid_ad:route&er_name=gridad&action=' + self.action + '&ad_id=' + self.form.id,
                        type: 'POST',
                        dataType: 'json',
                        data: {
                            formhash: FORMHASH,
                            data: self.form
                        },
                        success: function(response) {
                            if(response && response.success) {
                                alert(response.message || '广告申请已提交！');
                                location.reload();
                            } else {
                                alert(response.message || '提交失败，请稍后重试');
                            }
                        },
                        error: function(xhr, status, error) {
                            alert('网络错误，请稍后重试');
                        }
                    });
                },
                hideDialog() {
                    hideWindow('dialog');
                    var dialog = document.getElementById('fwin_dialog');
                    var cover = document.getElementById('fwin_dialog_cover');
                    if (dialog && dialog.parentNode) {
                        dialog.parentNode.remove();
                    }
                    if (cover) {
                        cover.remove();
                    }
                }
            }
        });
    }
})(jQuery);
</script>